package com.example.edums.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.edums.dao.UserMapper;
import com.example.edums.dto.LoginDTO;
import com.example.edums.dto.UserDTO;
import com.example.edums.entity.User;
import com.example.edums.service.UserService;
import com.example.edums.util.JwtUtil;
import com.example.edums.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Result<UserDTO> login(LoginDTO loginDTO) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", loginDTO.getUsername()));
        if (user == null || !passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            return Result.error(401, "用户名或密码错误");
        }

        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        userDTO.setToken(jwtUtil.generateToken(user.getUsername()));

        return Result.success(userDTO);
    }

    @Override
    public Result<List<User>> getAllUsers() {
        List<User> users = userMapper.selectList(null);
        return Result.success(users);
    }

    @Override
    public Result<User> addUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return Result.success(user);
    }

    @Override
    public Result<User> updateUser(Long id, User user) {
        user.setId(id);
        if (user.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }
        userMapper.updateById(user);
        return Result.success(user);
    }

    @Override
    public Result<Void> deleteUser(Long id) {
        userMapper.deleteById(id);
        return Result.success(null);
    }
}